﻿// JScript 文件

//////////Begin 控件的扩展///////////
if(!window.Prototype)
{
    alert("请加载Prototype.js");
}
if (!window.CtnPubDef)
{
    window.CtnPubDef = top.CtnPubDef;
}
if (!window.CtnMajorDef)
{
    window.CtnMajorDef = top.CtnMajorDef;
}
if (!window.CtnMinorDef)
{
    window.CtnMinorDef = top.CtnMinorDef;
}
if (!window.CtnDlgCtrl)
{
    window.CtnDlgCtrl = top.CtnDlgCtrl;
}
if (!window.CtnTool)
{
    window.CtnTool = top.CtnTool;
}
if (!window.m_vt)
{
    window.m_vt = top.m_vt;
}
if (window.CtnListCtrl)
{
    CtnListCtrl.prototype.onShowMsg = function (msg){
        top.CtnDlg.error(msg);
    }
}
if (window.CtnTreeCtrl)
{
    CtnTreeCtrl.prototype.onShowMsg = function (msg){
        top.CtnDlg.error(msg);
    }
}
//////////End 控件的扩展///////////

//////////Begin 全局变量///////////
var TEL_JS_VER = "1.0"; //用于辨别是否已加载var m_debug = true;     //
//////////End 全局变量/////////////


//////////Begin 对话框///////////
CtnDlg = {
    //警告
    warning: function(msg){
        var dlg = new CtnDlgCtrl();
        var params = {
            title: "警告",
            content: msg,
            bmodal: true,
            bmax: false,
            bmin:false,
            width:200,
            iconcss:CtnDlgCtrl.icon.WARNING,
            bresize:false,
            arrbtn: [{text:"确定", onClick:function(dlg){dlg.close();}}]
        }
        dlg.init(params);
        dlg.open();
        return dlg;
    },
    //错误提示
    error: function(msg){
        var dlg = new CtnDlgCtrl();
        var params = {
            title: "错误",
            content: msg,
            bmax: false,
            bmin:false,
            bmodal: true,
            minwidth:200,
            iconcss:CtnDlgCtrl.icon.ERROR,
            bresize:false,
            arrbtn: [{text:"确定", onClick:function(dlg){dlg.close();}}]
        }
        dlg.init(params);
        dlg.open();
        return dlg;
    },
    //提示框
    msg: function(msg, params, group){
        if (group)
        {
            var arrDlg = CtnDlgCtrl.arrDlg;
            for (var i = 0; i < arrDlg.length; i++)
            {
                if (arrDlg[i].CTNGROUP == "G" + group)
                {
                    arrDlg[i].reset(params);
                    return arrDlg[i];
                }
            }
        }
        var dlg = new CtnDlgCtrl();
        var param = {
            title: "提示",
            content: msg,
            bmax: false,
            bmin:false,
            bmodal: true,
            width:200,
            iconcss:CtnDlgCtrl.icon.MSG,
            bresize:false,
            arrbtn: [{text:"确定", onClick:function(dlg){dlg.close();}}]
        }
        if (params)
        {
            Object.extend(param, params);
        }
        if (group)
        {
            dlg.CTNGROUP == "G" + group;//加"G"避免与未定义组冲突
        }
        else
        {
            dlg.CTNGROUP == CtnDlgCtrl.dlgIdx;
        }
        dlg.init(param);
        dlg.open();
        return dlg;
    },
    //加载
    //msg:信息
    //func:回调
    //group:分组
    loading: function(msg, func, group, dlgParam){
        if (!msg)
        {
            msg = "系统忙，请稍候...";
        }
//        if (!flag && !func)
//        {
//            if (group)
//            {
//                setTimeout("CtnDlg.loading('" + msg + "',null, '" + group + "', 1)",1);
//            }
//            else
//            {
//                setTimeout("CtnDlg.loading('" + msg + "',null, null, 1)",1);
//            }
//            return ;
//        }
        var params = {
            title: "加载中...",
            content: '<table style="text-align:center; vertical-align:middle;width:100%;height:100%"><tr><td><div class="loadingimg">&nbsp;</div></td></tr><tr><td>' + msg + '</td></tr></table>',
            bmax: false,
            bmin:false,
            bclose: false,
            bmodal: true,
            width:200,
            iconcss:CtnDlgCtrl.icon.LOADING,
            bresize:false
        }
        if (func)
        {
            params.arrbtn =  [{text:"取消", onClick:func}];
        }
        if (dlgParam)
        {
            for (var k in dlgParam)
            {
                params[k] = dlgParam[k];
            }
        }
        if (group)
        {
            if (!this.LoadingCtrl[group])
            {
                this.LoadingCtrl[group] = new CtnDlgCtrl();
                this.LoadingCtrl[group].init(params);
                this.LoadingCtrl[group].open();
                return this.LoadingCtrl[group];
            }
            else
            {
                this.LoadingCtrl[group].reset(params);
                return this.LoadingCtrl[group];
            }
        }
        else
        {
            if (!this.LoadingDlg)
            {
                this.LoadingDlg = new CtnDlgCtrl();
                this.LoadingDlg.init(params);
                this.LoadingDlg.open();
            }
            else
            {
                this.LoadingDlg.reset(params);
            }
        }
        return this.LoadingDlg;
    },
    //停止加载
    unloading: function(dlg){
        if (dlg && typeof(dlg) == "object")
        {
            dlg.close();
            this.LoadingDlg = null;
        }
        else if (dlg)
        {
            this.LoadingCtrl[dlg].close();
            this.LoadingCtrl[dlg] = null;
        }
        else if (this.LoadingDlg)
        {
            this.LoadingDlg.close();
            this.LoadingDlg = null;
        }
    },
    //确认框
    confirm: function(msg, fun, funParam){//注意：回调函数中如果有
        var dlg = new CtnDlgCtrl();
        var params = {
            title: "确定",
            content: msg,
            bmax: false,
            bmin:false,
            bmodal:true,
            width:200,
            iconcss:CtnDlgCtrl.icon.QUESTION,
            bresize:false,
            arrbtn: [{text:"确定", onClick:function(dlg){dlg.close();fun(true, funParam);}},{text:"取消", onClick:function(dlg){dlg.close();fun(false, funParam);}}]
        }
        dlg.init(params);
        dlg.open();
        return dlg;
    },
    //msg:提示信息
    //defvalue:初始值
    prompt: function(msg, defValue, fun, funParam){//注意：回调函数中如果有
    
        var inputId = "dlg_" + new Date().getTime();
        var content = '<table style="width:100%;height:100%">'
                + '<tr><td>'
                + msg
                +'</td></tr>'
                + '<tr><td style="text-align:center;"><input value="' + defValue + '" id="' + inputId + '"  style="width:95%;" /></td></tr></table>';
        var dlg = new CtnDlgCtrl();
        var params = {
            title: "提示",
            content: content,
            bmax: false,
            bmin:false,
            bmodal:true,
            width:200,
            iconcss:CtnDlgCtrl.icon.NONE,
            bresize:false,
            arrbtn: [{text:"确定",
                      onClick:function(dlg){
                        var val = $F(inputId);
                        dlg.close();
                        //document.getElementById
                        fun(val, funParam);}},
                     {text:"取消",
                     onClick:function(dlg){
                        dlg.close();
                        //fun(false, funParam);
                        }}]
        }
        dlg.init(params);
        dlg.open();
        return dlg;
    },
    //打开表单
    //dlgParam:对话框参数title,width,height
    //inputParam:{id:{text:"ID0"},name:{text:"名称"}}
    form: function(inputParam, dlgParam, fun, funParam){//注意：回调函数中如果有
        var idx = new Date().getTime();
        var content = '<table style="width:100%;height:100%">';
        for (var key in inputParam)
        {
            if (!inputParam[key]['type'])
            {
                inputParam[key]['type'] = "text";
            }
            content += '<tr><td>';
            content += inputParam[key].text;
            content += '</td><td style="text-align:center;"><input ';
            content += ' id="' + key + '_' + idx + '"';
            for (var k in inputParam[key])
            {
                if (k == "text")
                {
                    continue;
                }
                content += ' ' + k + '="' + inputParam[key][k] + '"';
            }
            content += ' /></td></tr>';
        }
        content +='</table>';
        var dlg = new CtnDlgCtrl();
        dlg.arrbtn=[{text:"确定",
                      onClick:function(dlg){
                        var inputs = {};
                        for (var key in inputParam)
                        {
                            inputs[key] = $(key + "_" + idx);
                        }
                        dlg.close();
                        fun(inputs, funParam);}},
                     {text:"取消",
                     onClick:function(dlg){
                        dlg.close();
                        }}];
        dlg.content = content;
        dlg.init(dlgParam);
        dlg.open();
        return dlg;
    },
    //listctrl(只能使用top.CtnDlg.list)
    list: function(listParams, dlgParams){
        var id = "dl_" + this.listIdx++;
        var dlg = new CtnDlgCtrl();
        dlg.content = "&nbsp;";
        dlg.bmodal = false;
        dlg.init(dlgParams);
        dlg.open();
        
        dlg.element.elemBody.id = id;
        dlg.element.elemBody.style.overflow = "auto";
        //dlg.element.style.overflow = "hidden";
        CtnDlg.ListCtrl[id] = new CtnListCtrl("CtnDlg.ListCtrl." + id);
        CtnDlg.ListCtrl[id].create(id);
        for (var key in listParams)
        {
            CtnDlg.ListCtrl[id][key] = listParams[key];
        }
        //调整大小
        dlg.onResize = CtnDlg.ListCtrl[id].resetFlow.bind(CtnDlg.ListCtrl[id]);
        dlg.LIST = CtnDlg.ListCtrl[id];
        return dlg;
    },
    //打开页面
    open: function(url, params, group){
        if (group)
        {
            var arrDlg = CtnDlgCtrl.arrDlg;
            for (var i = 0; i < arrDlg.length; i++)
            {
                if (arrDlg[i].CTNGROUP == "G" + group)
                {
                    arrDlg[i].reset(params);
                    return arrDlg[i];
                }
            }
        }
        var dlg = new CtnDlgCtrl();
        dlg.url = url;
        dlg.bmodal = false;
        if (group)
        {
            dlg.CTNGROUP == "G" + group;//加"G"避免与未定义组冲突
        }
        else
        {
            dlg.CTNGROUP == CtnDlgCtrl.dlgIdx;
        }
        dlg.init(params);
        dlg.open();
        return dlg;
    },
    //打开内容
    show: function(content,params){
        var dlg = new CtnDlgCtrl();
        dlg.content = content;
        dlg.bmodal = true;
        dlg.init(params);
        dlg.open();
        return dlg;
    },
    LoadingCtrl:{},
    ListCtrl: {},
    listIdx: 0
}
//////////Begin 对话框///////////

//////////Begin 错误处理//////////
function CtnError(errStr, errCode, retCode)
{
    this.errStr = errStr;//错误信息
    this.errCode = errCode;//错误代码
    this.retCode = retCode;// 返回值
    this.name = "CtnError"; //名称,错误类别
    this.line    = -1;    //行号
    this.path = document.location.herf;    //文件名
}
CtnError.arrError = new Array();
CtnError.bDebug = m_debug;
CtnError._Method= {
    //验证param可以是文本也可以是xml对象,如果是XML对象，会验证其合法性
    validate: function(param){
        var xmlDoc = null;
        if (param == null)
        {
            this.objErr = new CtnError("对象为空！", CtnPubDef.ERR_NOXML, 100002);
            return false;
        }
        else if (typeof(param) == 'object')
        {
            xmlDoc = param;
            CtnXML.clearSpace(xmlDoc);
            if (xmlDoc.childNodes.length < 1 || xmlDoc.childNodes[0].tagName == "parsererror")
            {
                this.objErr = new CtnError("XML数据不合法！", CtnPubDef.ERR_NOXML, 100002);
                return false;
            }
        }
        else if(typeof(param) == 'string')
        {
            xmlDoc = CtnXML.getXmlDoc();
            xmlDoc.loadXML(param);
            CtnXML.clearSpace(xmlDoc);
        }
        var rootNode = xmlDoc.selectSingleNode("ErrProc");
        if (rootNode)
        {
            var errStr =  CtnXML.getValue(xmlDoc.selectSingleNode("ErrProc/ErrStr"));
            var errCode = CtnXML.getValue(xmlDoc.selectSingleNode("ErrProc/ErrCode"));
            var retCode = CtnXML.getValue(xmlDoc.selectSingleNode("ErrProc/retCode"));
            this.objErr = new CtnError(errStr, errCode, retCode);
            return false;
        }
        return true;
    },
    //存储调试信息
    debug: function(e){
        if (CtnError.bDebug)
        {
            CtnError.arrError.push(this.convert(e));
        }
    },
    //显示最近的错误信息
    show: function(e){
        if (e)
        {
            var err = this.convert(e);
            CtnDlg.error(err.errStr);
        }
        else if (this.objErr)
        {
            if (this.objErr.errCode == CtnPubDef.ERR_NOLOGIN)//如果是未登陆引起的，则弹出登陆对话框
            {
                var path = top.location.pathname.substr(0, top.location.pathname.lastIndexOf("/"));
                top.CtnDlg.open(path + "/Login.aspx?" + new Date().getTime(), {title:"重新登陆", width:700,height:440, bmodal:true,bmin:false,bmax:false});
            }
            else
            {
                CtnDlg.error(this.objErr.errStr);
            }
        }
    },
    //输出所有调试信息
    showAll: function()
    {
        if (!CtnError.bDebug || CtnError.arrError.length < 1)
        {
            return;
        }
        var errStr = "";
        for (var i = 0; i < CtnError.arrError.length; i++)
        {
            errStr += CtnError.arrError[i].errStr + "<br/>";
        }
        CtnDlg.error(errStr);
    },
    //将各种错误信息转为标准的CtnError
    //e:可以是Error,CtnError,String,Number等
    convert: function(e)
    {
        var err = null;
        if (CtnError.prototype.isPrototypeOf(e))
        {
            err = e;
        }
        else if(Error.prototype.isPrototypeOf(e) && e.description)
        {
            err = new CtnError(e.message, e.number & 0xFFFF);
            err.name = e.name;
        }
        else if(Error.prototype.isPrototypeOf(e) && !e.description)
        {
            err = new CtnError(e.message);
            err.name = e.name;
            err.line = e.lineNumber;
            err.file = e.filename;
        }
        else
        {
            err = new CtnError(new String(e));
        }
        return err;
    },
    //清除错误信息
    clear: function(){
        while(CtnError.arrError.length > 0)
        {
            CtnError.arrError.pop();
        }
    }
}
Object.extend(CtnError, CtnError._Method);
//////////End 错误处理//////////

//////////Begin String对象的扩展//////////
CtnString = {
    isNumber: function(){isNaN(parseInt(this));},
    isInt: function(){isNaN(parseInt(this));},
    isFloat:function(){isNaN(parseFloat(this));},
    toInt: function(){return parseInt(this);},
    toFloat: function(){return parseFloat(this);},
    lTrim: function () {return this.replace(/^\s*/, "");},
    rTrim: function () {return this.replace(/\s*$/, "");},
    trim: function () {return this.strip();}//
}
Object.extend(String.prototype, CtnString);
//////////End String对象的扩展//////////
CtnArray = {
    //数组中是否存在某值
    contains: function(v){
        var flag = false;
        for (var i = 0; i < this.length; i++)
        {
            if (this[i]==v)
            {
                flag=true;break;
            }
        };
        return flag;
    }
}
Object.extend(Array.prototype, CtnArray);
//////////Begin prototype的补充//////////
//对浏览器的补充//主要有四个:IE:是否IE(来自prototype)
CtnBrowser = {
    IE6: navigator.userAgent.indexOf('MSIE 6') > -1,//是否IE6
    IE7: navigator.userAgent.indexOf('MSIE 7') > -1,//是否IE7
    FF: navigator.userAgent.indexOf('Firefox') > -1//是否FireFox
}

Object.extend(CtnBrowser, Prototype.Browser);
//////////End prototype的补充//////////

//////////Begin 文件传输//////////
//同步获取Response对象
CtnTrans = {
    getResponse: function(url, method, params){
        //获取虚拟目录
        var path = top.location.pathname.substr(0, top.location.pathname.lastIndexOf("/"));
        //暂时对使用非绝对路径Url进行处理
//        url = url.trim();
//        if (url.charAt(0) != "/")
//        {
//            var idx = url.indexOf("../");
//            while(idx == 0)
//            {
//                url = url.substring(3);
//                idx = url.indexOf("../");
//            }
//            url = path + "/" + url;
//        }
//        else
//        {
            url = path + url;
//        }
        
        var xmlreq = Ajax.getTransport();
        if (!method)
        {
            method = "get";
        }
        if (!params)
        {
            params = "";
        }
        else if (method.toLowerCase() == "get")
        {
            var idx = url.indexOf("?");
            if (idx > -1)
            {
                params = url.substring(idx + 1, url.length - 1) + "&" + params;
            }
            url += "?" + params;
        }
        
        try
        {
            xmlreq.open(method, url, false);
            xmlreq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            if (method.toLowerCase() == "post")
            {
                xmlreq.setRequestHeader("Content-Length",params.length);
                xmlreq.send(params);
            }
            else
            {
                xmlreq.send(null);
            }
            return xmlreq;
        }
        catch(e)
        {
            return null;
        }
    },
    //获取文本
    getText: function(url, method, params){
        var xmlreq = this.getResponse(url, method, params);
        if (xmlreq)
        {
            return xmlreq.responseText;
        }
        return null;
    },
    //获取XML
    getXml: function(url, method, params)
    {
        var text = this.getText(url, method, params);
        var xmlDoc = CtnXML.getXmlDoc();
        if (xmlDoc&&text!==null)
        {
            xmlDoc.loadXML(text);
            return xmlDoc;
        }
        return null;
    },
    //Ajax异步传输,url:地址,_method:传输方式(post,get),params:post参数,complete:回调函数,funcParams:回调参数
    //others:其他参数(loading:是否进度条，loadingText:进度信息,loadingGroup:进度分组)
    //回调函数function (response, funcParams)
    Ajax: function(url, _method, params, complete, funcParams, others){
            var path = top.location.pathname.substr(0, top.location.pathname.lastIndexOf("/"));
            url = url.trim();
            url = path + url;
            if (!others)
            {
                others = {};
            }
            others.method = _method;
            others.parameters = params;
            others.funcComplete = complete;
            others.funcParams = funcParams;
            others.onComplete = (function (response){
                if (this.loading && this.loadingGroup)
                {
                    var objLoading = CtnTrans.Ajax.LoadingCtrl[this.loadingGroup];
                    if (objLoading.arrAjax.length <= 1)
                    {
                        CtnDlg.unloading(this.loadingGroup);
                        CtnTrans.Ajax.LoadingCtrl[this.loadingGroup] = null;
                    }
                    else
                    {
                        for (var i = 0; i < objLoading.arrAjax.length; i++)
                        {
                            if (objLoading.arrAjax[i] == this.ajax)
                            {
                                objLoading.arrAjax.splice(i, 1);
                                CtnDlg.loading(this.loadingText + "<br />已完成" + (objLoading.max - objLoading.arrAjax.length) + "/" + objLoading.max, null, this.loadingGroup);
                                break;
                            }
                        }
                    }
                }
                else if (this.loadingDlg)
                {
                    CtnDlg.unloading(this.loadingDlg);
                }
                
                if (this.funcComplete)
                {
                    this.funcComplete(response, this.funcParams);
                };
            }).bind(others);
            if (others.loading)
            {
                if (others.loadingGroup && !CtnTrans.Ajax.LoadingCtrl[others.loadingGroup])
                {
                    CtnTrans.Ajax.LoadingCtrl[others.loadingGroup] = {};
                    CtnTrans.Ajax.LoadingCtrl[others.loadingGroup].max = 0;
                    CtnTrans.Ajax.LoadingCtrl[others.loadingGroup].arrAjax = new Array();
//                    CtnTrans.Ajax.LoadingCtrl[others.loadingGroup].dlg = CtnDlg.loading(
//                        others.loadingText,
//                        (function(dlg)
//                        {
//                            var arrAjax = CtnTrans.Ajax.LoadingCtrl[this.loadingGroup].arrAjax;
//                            while(arrAjax.length > 0)
//                            {
//                                arrAjax.pop().transport.abort();
//                            }
//                            dlg.close();
//                            CtnTrans.Ajax.LoadingCtrl[this.loadingGroup] = null;
//                        }).bind(others)
//                    );
                }
                else if (!others.loadingGroup)
                {
                    dlg = CtnDlg.loading(others.loadingText, (function(dlg){this.ajax.transport.abort();dlg.close();}).bind(others));
                    others.loadingDlg = dlg;
                }
            }
            if (others.showError == null || others.showError)
            {
                others.onFailure = function (){
                    CtnDlg.error("服务器错误:" + 
				        "<br/> readyState:" + this.req.readyState
				        + "<br/> status:" + this.req.status
				        + "<br/> headers: " + this.req.getAllResponseHeaders());
                }
            }
            var ajax = new Ajax.Request(url, others);
            if (others.loading && others.loadingGroup)
            {
                var objLoading = CtnTrans.Ajax.LoadingCtrl[others.loadingGroup];
                objLoading.arrAjax.push(ajax);
                objLoading.max++;
                if (!others.loadingText){others.loadingText = "正在加载... "}
                CtnDlg.loading(others.loadingText + "<br />已完成" + (objLoading.max - objLoading.arrAjax.length) + "/" + objLoading.max, 
                    (function(dlg)
                        {
                            var arrAjax = CtnTrans.Ajax.LoadingCtrl[this.loadingGroup].arrAjax;
                            while(arrAjax.length > 0)
                            {
                                var aj = arrAjax.pop();
                                aj.options.onComplete = null;
                                aj.transport.abort();
                            }
                            dlg.close();
                            CtnTrans.Ajax.LoadingCtrl[this.loadingGroup] = null;
                        }).bind(others)
                , others.loadingGroup);
            }
            others.ajax = ajax;
        }
}
CtnTrans.Ajax.LoadingCtrl = {};

//////////End 文件传输//////////

//////////Begin 动态操作CSS//////////
CtnCss = {
     GetCurrentStyle: function(obj, prop) {//获取当前某元素的Style属性值,如GetCurrentStyle("Div1","height");
	    if (obj.currentStyle) {
		    return obj.currentStyle[prop];
	    }
	    else if (window.getComputedStyle) {
		    prop = prop.replace (/([A-Z])/g, "-$1");
		    prop = prop.toLowerCase ();
		    return window.getComputedStyle(obj, "").getPropertyValue(prop);
	    }
	    return null;
    }
}

//////////End 动态操作CSS//////////

//////////Begin 动态操作JS//////////

CtnJS = {
    includeJs: function(path){//动态加载js
        var protocol = window.location.protocol;
        var host = window.location.host;
        var curPath = window.location.pathname;
        var url = "";
        if (path.indexOf('/') == 0)
        {
            url = protocol + "//" + host + path;
        }
        else
        {
            var idx = curPath.lastIndexOf("/");
            url = protocol + "//" + host + curPath.substring(0, idx) + "/" + path;
        }
        url = url.toLowerCase();
        scripts = document.getElementsByTagName("script");
        for (var i = 0; i < scripts.length; i++)
        {
            var src =  scripts[i].src.toLowerCase();
            if (url.lastIndexOf(src) > -1)
            {
                return null;
            }
        }
        var id = escape(path);
        var vText = CtnTrans.getText(path);
        if ((vText != null) && (!document.getElementById(id)))
        {
            var head = document.getElementsByTagName("head")[0];
            var script = document.createElement("script");
            script.language = "javascript";
            script.type = "text/javascript";
            script.defer = true;
            script.text = vText;
            head.appendChild(script);
        }
    }
}

//////////End 动态操作JS//////////

//////////Begin Cookies//////////
CtnCookie = {
    get : function(n){//获取变量值
        var dc = "; "+document.cookie+"; ";
        var coo = dc.indexOf("; "+n+"=");
        if (coo!=-1){
            var s = dc.substring(coo+n.length+3,dc.length);
            return unescape(s.substring(0, s.indexOf("; ")));
        }else{
            return null;
        }
    },
    set : function(name,value,expires,path,domain,secure){//设置值，除了name,value其余可选
        var expDays = expires*24*60*60*1000;
        var expDate = new Date();
        expDate.setTime(expDate.getTime()+expDays);
        var expString = expires ? "; expires="+expDate.toGMTString() : "";
        var pathString = "; path="+(path||"/");
        var domain = domain ? "; domain="+domain : "";
        document.cookie = name + "=" + escape(value) + expString + domain + pathString + (secure?"; secure":"");
    },
    del : function(n){//删除变量
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        var cval=this.get(n);
        if(cval!=null) document.cookie= n + "="+cval+";expires="+exp.toGMTString();
    }
}
//////////End Cookies//////////

////////////Begin XML操作//////////////////
CtnXML = {
    getXmlDoc: function(){//获取XML文档对象
        var XmlVal = null ;
        try
        {
            XmlVal = new ActiveXObject("Msxml2.DOMDocument.4.0") ;
        }
        catch(e)
        {
            try
            {
                XmlVal = new ActiveXObject("Microsoft.XMLDOM") ;
            }
            catch(o)
            {
                if(document.implementation 
                    && document.implementation.createDocument
                    && document.implementation.hasFeature("XPath", "3.0"))
                {
                    XmlVal = document.implementation.createDocument('','',null);
                }
            }
        }
        return XmlVal;
    },
    getRootNode: function(xmlDoc){//获取XML根节点
        this.clearSpace(xmlDoc);
        if (xmlDoc.childNodes.length < 1)
        {
            return null;
        }
        var rootNode = null;
        if (xmlDoc.childNodes[0].nodeName != "xml")
        {
            rootNode = xmlDoc.childNodes[0];
        }
        else if (xmlDoc.childNodes.length > 1)
        {
            rootNode = xmlDoc.childNodes[1];
        }
        return rootNode;
    },
    clearSpace: function(elem){//清除XML空白节点
        if(!elem || !elem.nodeType)
        {
            return;
        }
        for (var i = elem.childNodes.length - 1; i >= 0 ; i--)
        {
            if (elem.childNodes[i].nodeType != 1)
            {
                var text = elem.childNodes[i].nodeValue;
                text = text.replace(new RegExp("(^[ \f\n\r\t\v]*)|([ \f\n\r\t\v]*$)","g"),"");
                if (!text)
                {
                    elem.removeChild(elem.childNodes[i]);
                }
            }
        }
    },
    getValue: function(xmlNode){//获取节点值
        if (!xmlNode)
        {
            return null;
        }
        if (xmlNode.text)
        {
            return xmlNode.text;
        }
        else
        {
            return xmlNode.textContent;
        }
    },
    getAttr: function(xmlNode, attr){//节点属性值
        if (!xmlNode)
        {
            return null;
        }
        return xmlNode.getAttribute(attr);
    }
}
//获取XML节点值 $XML(node);$XML(node,null,"int");
//获取XML节点属性值 $XML(node,attr);$XML(node,attr,"int");
function $XML(xmlNode, attrName, parseType)
{
    if (!xmlNode)
    {
        return null;
    }
    var vText = null;
    
    if (attrName)//取节点属性
    {
        vText = xmlNode.getAttribute(attrName);
    }
    else//取节点值
    {
        if (xmlNode.text)
        {
            vText = xmlNode.text;
        }
        else
        {
            vText = xmlNode.textContent;
        }
    }
    
    if (!parseType)
    {
        return vText;
    }
    
    if (parseType.toLowerCase() == "int")
    {
        return parseFloat(vText);
    }
    else if (parseType.toLowerCase() == "float")
    {
        return parseFloat(vText);
    }
    else
    {
        return vText;
    }
}

//对火狐XML节点添加selectNodes和selectSingleNode方法
CtnXML._Method = {
    XMLDocument : function(){
        this.loadXML = function(xmlString){
            var childNodes = this.childNodes;
            for (var i = childNodes.length - 1; i >= 0; i--)
                this.removeChild(childNodes[i]);

            var dp = new DOMParser();
            var newDOM = dp.parseFromString(xmlString, "text/xml");
            var newElt = this.importNode(newDOM.documentElement, true);
            this.appendChild(newElt);
        };
        this.selectNodes = function(cXPathString, xNode){
          if( !xNode ) { xNode = this; } 
          var oNSResolver = this.createNSResolver(this.documentElement)
          var aItems = this.evaluate(cXPathString, xNode, oNSResolver, 
                       XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
          var aResult = [];
          for( var i = 0; i < aItems.snapshotLength; i++)
          {
             aResult[i] =  aItems.snapshotItem(i);
          }
          return aResult;
       };
       this.selectSingleNode = function(cXPathString, xNode){
          if( !xNode ) { xNode = this; } 
          var xItems = this.selectNodes(cXPathString, xNode);
          if( xItems.length > 0 )
          {
             return xItems[0];
          }
          else
          {
             return null;
          }
       };
    },
    XMLElement : function(){
        this.selectNodes = function(cXPathString){
          if(this.ownerDocument.selectNodes)
          {
             return this.ownerDocument.selectNodes(cXPathString, this);
          }
          else
          {
            throw "只对XML节点有效！";
          }
       };
       this.selectSingleNode = function(cXPathString){    
          if(this.ownerDocument.selectSingleNode)
          {
             return this.ownerDocument.selectSingleNode(cXPathString, this);
          }
          else
          {
            throw "只对XML节点有效！";
          }
       };
    }
}

if (!window.attachEvent&&!XMLDocument.loadXML)
{
    CtnXML._Method.XMLDocument.apply(XMLDocument.prototype);
    CtnXML._Method.XMLElement.apply(Element.prototype);
}
/////////////End XML操作//////////////////
/////////////Begin 兼容性操作/////////////
function $V(elem, value)
{
    if (!elem)
    {
        return null;
    }
    else if (elem != "object")
    {
        elem = $(elem);
    }
    if (elem.tagName.toLowerCase() == "input"
        || elem.tagName.toLowerCase() == "select"
        || elem.tagName.toLowerCase() == "textarea"
        || elem.tagName.toLowerCase() == "button")
    {
        if (value != null)
        {
            elem.value = value;
        }
        else
        {
            return elem.value;
        }
    }
    else if (CtnBrowser.IE)
    {
        if (value != null)
        {
            elem.innerText = value;
        }
        else
        {
            return elem.innerText;
        }
    }
    else
    {
        if (value != null)
        {
            elem.textContent = value;
        }
        else
        {
            return elem.textContent;
        }
    }
}
////////////// Begin Excel操作/////////////////////
CtnExcel = {
    ExpByTable : function(tabid, outputFile, templateFile, sheetIndex, startRow, startCol)
    {
        var tab = $(tabid);
        if (!tab)
        {
            top.error("表格" + tabid + "不存在!");
            return;
        }
        tab.cleanWhitespace();
        //找tr的上一级，不是table,就是tbody
        for (var i = 0; i < tab.childNodes.length; i++)
        {
            var tag = tab.childNodes[i].tagName.toUpperCase();
            if(tag == "TBODY")
            {
                tab = tab.childNodes[i];
                $(tab).cleanWhitespace();
                break;
            }
            else if (tag == "TR" || tag == "TH")
            {
                break;
            }
        }
        //构造XML
        var xmlBuf = new Array();
        xmlBuf.push("<i>");
        for (var i = 0; i < tab.childNodes.length; i++)
        {
            var tr = tab.childNodes[i];
            $(tr).cleanWhitespace();
            xmlBuf.push("<j>");
            for (var j = 0; j < tr.childNodes.length; j++)
            {
                xmlBuf.push("<k>");
                xmlBuf.push($V(tr.childNodes[j]));
                xmlBuf.push("</k>");
            }
            xmlBuf.push("</j>");
        }
        xmlBuf.push("</i>");
        this.ExpByXmlData(xmlBuf.join(""), outputFile, templateFile, sheetIndex, startRow, startCol);
    },
    ExpByUser : function (_method, params, outputFile)
    {
        CtnTrans.Ajax("/Main.ashx?_method=" + _method,"post"
            , params, this.getExcel, outputFile, {loading:true,loadingText:"正在创建Excel..."});
    },
    ExpByXmlDoc : function(XmlDoc, outputFile, templateFile, sheetIndex, startRow, startCol)
    {
        //makeExcel("ExpByXmlData", XmlData, outputFile, templateFile, sheetIndex, startRow, startCol);
    },
    ExpByDtSrc : function(XmlData, outputFile, templateFile, sheetIndex, startRow, startCol)
    {
        this.makeExcel("ExpByDtSrc", XmlData, outputFile, templateFile, sheetIndex, startRow, startCol);
    },
    ExpByLrtSrc : function(XmlData, outputFile, templateFile, sheetIndex, startRow, startCol)
    {
        this.makeExcel("ExpByLrtSrc", XmlData, outputFile, templateFile, sheetIndex, startRow, startCol);
    },
    ExpByArrSrc : function(XmlData, outputFile, templateFile, sheetIndex, startRow, startCol)
    {
        this.makeExcel("ExpByXmlData", XmlData, outputFile, templateFile, sheetIndex, startRow, startCol);
    },
    ExpByXmlData : function(XmlData, outputFile, templateFile, sheetIndex, startRow, startCol)
    {
        this.makeExcel("ExpByXmlData", XmlData, outputFile, templateFile, sheetIndex, startRow, startCol);
    },
    makeExcel : function(_method, DataSrc, outputFile, templateFile, sheetIndex, startRow, startCol)
    {
        if (!_method)
        {
            top.error("数据源不能为空!");
            return;
        }
        if (!DataSrc)
        {
            top.error("数据源不能为空!");
            return;
        }
        if (!outputFile)
        {
            top.error("输出文件名不能为空!");
            return;
        }
        var params = "Data=" + encodeURIComponent(DataSrc);
        if (templateFile)
        {
            params += "&File=" + encodeURIComponent(templateFile);
        }
        if (sheetIndex)
        {
            params += "&Idx=" + sheetIndex;
        }
        if (startRow)
        {
            params += "&Top=" + startRow;
        }
        if (startCol)
        {
            params += "&Left=" + startCol;
        }
        CtnTrans.Ajax("/Excel.ashx?_method=" + _method,"post"
            , params, this.getExcel, outputFile, {loading:true,loadingText:"正在创建Excel..."});
    },
    getExcel : function(res, filename)
    {
        var text = res.responseText;
        if (!CtnError.validate(text))
        {
            CtnError.show();
            return;
        }
//        var file = text.split("<>")[0];
//        if (!filename)
//        {
//            filename = text.split("<>")[1];
//        }
        var path = top.location.pathname.substr(0, top.location.pathname.lastIndexOf("/"));
        window.location.href = path + text;
        //window.location.href = path + "/Excel.ashx?_method=GetExcelFile&FileName=" + escape(filename) + "&FilePath=" + encodeURIComponent(file);
    },
    impExcel : function(form, userMethod)
    {
        var ifrm = $("ifrm_upfile");
        if (!ifrm)
        {
            ifrm = document.createElement("iframe");
            ifrm.style.display = "none";
            ifrm.id = "ifrm_upfile";
            ifrm.name = "ifrm_upfile"
            form.parentNode.appendChild(ifrm);
        }
        form.target = "ifrm_upfile";
        form.method = "post";
        form.action = "../Excel.ashx?_method=ImpExcel&UserMethod=" + userMethod;
        form.enctype ="multipart/form-data";
        return true;
    }
}
//////////////end Excel操作//////////////


//function escape(v)
//{
//    return encodeURIComponent(v);
//}
//function unescape(v)
//{
//    return decodeURIComponent(v);
//}
//function urlEncode(o, param)
//{
//    if(o == null)
//    {
//        return "";
//    }
//    else if (typeof(o) == 'string')
//    {
//        return encodeURIComponent(o);
//    }
//    else if (typeof(o) == 'boolean')
//    {
//        return new String(o);
//    }
//    else if (typeof(o) == 'object')
//    {
//        var buf = [];
//        if(o instanceof Array)
//        {
//            if (param != null)
//            {
//                k = param;
//            }
//            if (ov.length)
//            {
//                for(var i = 0, len = ov.length; i < len; i++)
//                {
//                    buf.push(k, "=", encodeURIComponent(ov[i] === undefined ? '' : ov[i]), "&");
//                }
//            }
//            else
//            {
//                buf.push(k, "=&");
//            }
//        }
//        for(var key in o)
//        {
//            var ov = o[key], k = encodeURIComponent(key);
//            var type = typeof ov;
//            if(type == 'undefined')
//            {
//                buf.push(k, "=&");
//            }
//            else if(type != "function" && type != "object")
//            {
//                buf.push(k, "=", encodeURIComponent(ov), "&");
//            }
//            else if(ov instanceof Array)
//            {
//                if (param != null)
//                {
//                    k = param;
//                }
//                if (ov.length)
//                {
//                    for(var i = 0, len = ov.length; i < len; i++)
//                    {
//                        buf.push(k, "=", encodeURIComponent(ov[i] === undefined ? '' : ov[i]), "&");
//                    }
//                }
//                else
//                {
//                    buf.push(k, "=&");
//                }
//            }
//        }
//        buf.pop();
//        return buf.join("");
//    }
//    else
//    {
//        return encodeURIComponent(o.toString());
//    }
//}
/////////////Begin 兼容性操作/////////////
/////////////Begin 公用函数 ///////////
CtnFunc = {
    XmlToObj : function(node){//Xml节点转为对象
        var obj = {};
        CtnXML.clearSpace(node);
        for (var i = 0; i < node.childNodes.length; i++)
        {
            if (node.childNodes[i].nodeType == 1)
            {
                
            }
        }
    }
}
/////////////End 公用函数 ///////////